package com.hxtec.polaris.service.impl;

import com.hxtec.polaris.commons.api.vo.Result;
import com.hxtec.polaris.commons.constant.Code;
import com.hxtec.polaris.commons.constant.GlobalVar;
import com.hxtec.polaris.commons.constant.Log;
import com.hxtec.polaris.commons.constant.Msg;
import com.hxtec.polaris.commons.exception.MyException;
import com.hxtec.polaris.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Map;

/**
 * @Describtion 文件服务
 * @Author yonyong
 * @Date 2019/12/18 14:35
 * @Version 1.0.0
 **/
@Service
@Transactional
public class FileServiceImpl implements FileService{

    private static final String LOG_CLASS_NAME = "FileServiceImpl";
    private static final String LOG_METHOD_UPLOAD_CATEGORY= "uploadCategoryImage";
    private static final String LOG_METHOD_UPLOAD_CAROUSE= "uploadCarouseImage";

    @Override
    public Object uploadCategoryImage(MultipartFile img, HttpServletRequest request) {
        try {
            return Result.ok(saveImg(img,request,GlobalVar.CATEGORY_IMG_PATH));
        }catch (Exception e){
            String params = "img="+img;
            String LOG_MSG = MessageFormat.format(Log.PATTERN_LOG,Log.INSERT,LOG_CLASS_NAME,LOG_METHOD_UPLOAD_CATEGORY,params);
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMMON_FAIL),LOG_MSG);
        }
    }

    @Override
    public Object uploadCarouseImage(MultipartFile file, HttpServletRequest request) {
        try {
            return Result.ok(saveImg(file,request,GlobalVar.CAROUSE_IMG_PATH));
        }catch (Exception e){
            String params = "img="+file;
            String LOG_MSG = MessageFormat.format(Log.PATTERN_LOG,Log.INSERT,LOG_CLASS_NAME,LOG_METHOD_UPLOAD_CAROUSE,params);
            throw new MyException(Result.error(Code.FAIL_4501, Msg.COMMON_FAIL),LOG_MSG);
        }
    }

    /**
     * 保存文件到指定目录，并返回路径
     * @param img   前端传递过来的图片
     * @param request
     * @param savePath 图片存储地址 为相对路径 严格遵守 upload/category 格式
     * @return String 返回图片的地址  http://127.0.0.1:9102/polaris/document/upload/category/test.jpg
     */
    private String saveImg(MultipartFile img, HttpServletRequest request, String savePath) throws IOException {
        String path = "error";
        if(!img.isEmpty()) {
            //原本的文件名
            //现在的文件名是时间戳加原文件名，出现图片相同时，读取不出来的bug
            String nowName = System.currentTimeMillis() + img.getOriginalFilename();
            //如果文件名太长，给图片重命名
            if (img.getOriginalFilename().length()>20){
                nowName = "图片-" +nowName.replaceAll(".+\\.", System.currentTimeMillis()+".");
//                nowName = "图片-" + System.currentTimeMillis();
            }
            //将文件保存在当前工程下的一个upload文件
            //将文件的输入流输出到一个新的文件
            FileUtils.copyInputStreamToFile(img.getInputStream(), new File(GlobalVar.UPLOAD_BASE_PATH+savePath, nowName));
            //getScheme 当前链接使用的协议  getServerName 服务器地址 getServerPort 端口号 getContextPath 应用名称
            path = request.getScheme()
                    + "://" + request.getServerName()
                    + ":" + request.getServerPort()
                    + request.getContextPath()
                    + "/" + GlobalVar.FILE_MAPPING_PATH
                    + "/" + savePath
                    + "/" + nowName;
            //将 \ 替换为 / 避免图片解析不出
            path = path.replaceAll("\\\\","/");
        }
        return path;
    }
}
